import React, { useState } from 'react'
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select,
  Tooltip,
  Progress
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  PlayCircleOutlined,
  PauseCircleOutlined,
  SyncOutlined
} from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { api } from '../services/api'

const { Option } = Select

const Connections: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [form] = Form.useForm()

  // 获取连接列表
  const { data: connections, isLoading, refetch } = useQuery({
    queryKey: ['connections'],
    queryFn: api.getConnections,
  })

  // 获取连接器列表用于选择
  const { data: connectors } = useQuery({
    queryKey: ['connectors'],
    queryFn: api.getConnectors,
  })

  const columns = [
    {
      title: '连接名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '同步模式',
      dataIndex: ['configuration', 'sync_mode'],
      key: 'sync_mode',
      render: (mode: string) => {
        const modeMap = {
          FullRefresh: { color: 'blue', text: '全量刷新' },
          Incremental: { color: 'green', text: '增量同步' },
          RealTime: { color: 'purple', text: '实时同步' },
        }
        const modeInfo = modeMap[mode as keyof typeof modeMap] || { color: 'default', text: mode }
        return <Tag color={modeInfo.color}>{modeInfo.text}</Tag>
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          Active: { color: 'green', text: '运行中' },
          Paused: { color: 'orange', text: '已暂停' },
          Error: { color: 'red', text: '错误' },
          Syncing: { color: 'blue', text: '同步中' },
        }
        const statusInfo = statusMap[status as keyof typeof statusMap] || statusMap.Paused
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>
      },
    },
    {
      title: '进度',
      key: 'progress',
      render: () => (
        <Progress 
          percent={Math.floor(Math.random() * 100)} 
          size="small" 
          status="active"
        />
      ),
    },
    {
      title: '最后同步',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (date: string) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Tooltip title={record.status === 'Active' ? '暂停' : '启动'}>
            <Button 
              type="text" 
              icon={record.status === 'Active' ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              onClick={() => handleToggleConnection(record)}
            />
          </Tooltip>
          <Tooltip title="立即同步">
            <Button 
              type="text" 
              icon={<SyncOutlined />} 
              onClick={() => handleSyncConnection(record.id)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEditConnection(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />} 
              onClick={() => handleDeleteConnection(record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ]

  const handleCreateConnection = () => {
    setIsModalVisible(true)
    form.resetFields()
  }

  const handleEditConnection = (connection: any) => {
    setIsModalVisible(true)
    form.setFieldsValue(connection)
  }

  const handleDeleteConnection = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个连接吗？此操作不可撤销。',
      onOk: async () => {
        try {
          await api.deleteConnection(id)
          refetch()
        } catch (error) {
          console.error('删除连接失败:', error)
        }
      },
    })
  }

  const handleToggleConnection = async (connection: any) => {
    try {
      if (connection.status === 'Active') {
        await api.stopConnection(connection.id)
      } else {
        await api.startConnection(connection.id)
      }
      refetch()
    } catch (error) {
      console.error('切换连接状态失败:', error)
    }
  }

  const handleSyncConnection = (id: string) => {
    Modal.info({
      title: '同步已启动',
      content: '连接同步已开始，请在仪表板查看进度。',
    })
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      await api.createConnection(values)
      setIsModalVisible(false)
      refetch()
    } catch (error) {
      console.error('创建连接失败:', error)
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h1>连接管理</h1>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreateConnection}
        >
          创建连接
        </Button>
      </div>

      <Table 
        columns={columns} 
        dataSource={connections} 
        loading={isLoading}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个连接`,
        }}
      />

      <Modal
        title="创建连接"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="连接名称"
            rules={[{ required: true, message: '请输入连接名称' }]}
          >
            <Input placeholder="输入连接名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={2} placeholder="输入连接描述" />
          </Form.Item>

          <Form.Item
            name="source_id"
            label="数据源"
            rules={[{ required: true, message: '请选择数据源' }]}
          >
            <Select placeholder="选择数据源连接器">
              {connectors?.filter((c: any) => c.connector_type === 'Source').map((connector: any) => (
                <Option key={connector.id} value={connector.id}>
                  {connector.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="destination_id"
            label="目标"
            rules={[{ required: true, message: '请选择目标' }]}
          >
            <Select placeholder="选择目标连接器">
              {connectors?.filter((c: any) => c.connector_type === 'Destination').map((connector: any) => (
                <Option key={connector.id} value={connector.id}>
                  {connector.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name={['configuration', 'sync_mode']}
            label="同步模式"
            rules={[{ required: true, message: '请选择同步模式' }]}
          >
            <Select placeholder="选择同步模式">
              <Option value="FullRefresh">全量刷新</Option>
              <Option value="Incremental">增量同步</Option>
              <Option value="RealTime">实时同步</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name={['configuration', 'schedule']}
            label="调度计划"
          >
            <Input placeholder="例如: 0 */5 * * * * (每5分钟)" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Connections
